package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private RedisTemplate redisTemplate;

    //文章审核
    public void examine(String articleId) {
        articleDao.updateStatus(articleId);
    }
    //文章点赞
    public void updateThumpup(String articleId) {
        Article article = (Article) redisTemplate.opsForValue().get("article_" + articleId);
        System.out.println("article = " + article);
        if(article==null){
        articleDao.updateThumpup(articleId);
            //调用dao根据id获取Article的值
            Article article1 = articleDao.findById(articleId).get();
            redisTemplate.opsForValue().set("article_"+articleId,article1);
        }
    }
     //开始从redis中查询此对象，如果没有就查询数据库
    public Article  findByid(String id){
        Article article = (Article) redisTemplate.opsForValue().get("article_" + id);
        //如果他等于空就获取值放进redis中
        if(article==null){
            //调用dao根据id获取Article的值
            Article article1 = articleDao.findById(id).get();
            redisTemplate.opsForValue().set("article_"+id,article1);
            //设置redis过期时间
            redisTemplate.opsForValue().set("article_"+id,article,10,TimeUnit.SECONDS);
        }
        //返回值
        return article;
    }
        //修改文章
        public void updateArticle(Article article){
                redisTemplate.delete("article_"+article.getId());
                articleDao.save(article);
        }
        //删除文章
    public void deleteArticle(String articleId){
        redisTemplate.delete("article_"+articleId);
        articleDao.deleteById(articleId);
    }
}
